package com.photoeditor.demo.ui.fragement.gallery;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.photoeditor.R;
import com.photoeditor.demo.app.XFragment;
import com.photoeditor.demo.model.bean.DateBean;
import com.photoeditor.demo.model.bean.ImageFolder;
import com.photoeditor.demo.model.bean.ThumbnailBean;
import com.photoeditor.demo.model.image.util.ImageHelper;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.model.share.ShareImageTools;
import com.photoeditor.demo.ui.activity.GalleryActivity;
import com.photoeditor.demo.ui.activity.edit.ImagePreviewActivity;
import com.photoeditor.demo.ui.adapter.gallery.FolderListAdapter;
import com.photoeditor.demo.ui.adapter.gallery.ICheckedChangeListener;
import com.photoeditor.demo.ui.adapter.gallery.IFaceDetectListener;
import com.photoeditor.demo.ui.adapter.gallery.IModeChangeListener;
import com.photoeditor.demo.ui.adapter.gallery.IOnFragmentChange;
import com.photoeditor.demo.ui.adapter.gallery.ListGridAdapter;
import com.photoeditor.demo.ui.adapter.share.ShareImageListAdapter;
import com.photoeditor.demo.ui.widget.share.ShareImageItem;
import com.photoeditor.demo.util.ArrayUtil;
import com.photoeditor.demo.util.AsyncTask;
import com.photoeditor.demo.util.IDeleteListener;
import com.photoeditor.demo.util.PermissionUtil;

import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
 * 其他相册的fragment
 */
public class OtherGalleryFragment extends XFragment implements IFaceDetectListener {

    private ArrayList<ImageFolder> mFolderInfo;

    private GalleryActivity mActivity;

    private View mContainerView;

    //空的时候的界面
    private View mEmptyGalleryView;

    private GridView mFolderView;

    private FolderListAdapter mFolderAdapter;

    /**
     * 分享相关
     */
    private View mShade;
    private View mSharePanel;
    private GridView mShareImageView;
    private ShareImageListAdapter mShareImageAdapter;

    private int mMode = MODE_FOLDER;

    public final static int MODE_FOLDER = 0;

    public final static int MODE_GALLERY = 1;

    private DateBean mNowTime;

    private final int COL_NUM = 3;
    private ListGridAdapter mGalleryAdapter;
    private ListView mGalleryListView;
    private View mListPanel;

    private int mSelectPosition = -1;

    /**
     * 删除时的验证Dialog
     */
    private AlertDialog mDeleteConfirmDialog;

    /**
     * 移入私密箱时的验证Dialog
     */
    private AlertDialog mPrivateConfirmDialog;

    private ProgressDialog mProgressDialog;

    private IFaceDetectListener mLoadingListener;

    public IModeChangeListener modeChangeListener = new IModeChangeListener() {

        @Override
        public void onModeChange(int mode, int position) {
            if (mode != mMode) {
                mMode = mode;
                mActivity.changUIForMode(mMode, position);
                if (mMode == MODE_FOLDER) {
                    mSelectPosition = -1;
                    showGalleryListView(false);
                    setFolderViewVisible(true);
                    refreshData();
                } else if (mMode == MODE_GALLERY) {
                    mSelectPosition = position;
                    showGalleryListView(true);
                    setFolderViewVisible(false);
                    startGettingGalleryDataTask(position);
                }
            }
        }
    };

    public OtherGalleryFragment() {

    }

    public OtherGalleryFragment(ICheckedChangeListener listener, IOnFragmentChange dataListener, IFaceDetectListener dListener) {
        mActivityListener = listener;
        mDataListener = dataListener;
        mLoadingListener = dListener;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = (GalleryActivity) getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View contanerView = inflater.inflate(R.layout.fragment_other_gallery, container, false);
        initView(contanerView);
        isCreated = true;
        mMode = MODE_FOLDER;
        setNeedRefresh(true);
        if (mDataListener != null) {
            mDataListener.onFragmentCreated(GalleryActivity.TYPE_FRAGMENT_OTHER_GALLERY);
        }
        return contanerView;
    }

    private void initView(View contanerView) {
        mContainerView = contanerView;
        mFolderView = (GridView) mContainerView.findViewById(R.id.folder_gridview);
        mShade = contanerView.findViewById(R.id.shade);
        initPermissionView();
    }

    private void initPermissionView() {
        if (PermissionUtil.needRequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            mContainerView.findViewById(R.id.layoutPermission).setVisibility(View.VISIBLE);
            mContainerView.findViewById(R.id.tvRequestPermission).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mActivity.handlePermission();
                }
            });
        } else {
            if (mContainerView.findViewById(R.id.layoutPermission).getVisibility() == View.VISIBLE) {
                mContainerView.findViewById(R.id.layoutPermission).setVisibility(View.GONE);
            }
        }
    }

    private void hidePermissionView() {
        if (!PermissionUtil.needRequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            if (mContainerView.findViewById(R.id.layoutPermission).getVisibility() == View.VISIBLE) {
                mContainerView.findViewById(R.id.layoutPermission).setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void startDetect() {
        mLoadingListener.startDetect();
    }

    @Override
    public void endDetect() {
        mLoadingListener.endDetect();
    }

    @Override
    public void onMoveClick(View v) {
        mGalleryAdapter.setCheckStatus(false);
    }

    @Override
    public boolean onBackClick(View v) {
        if (mMode == MODE_GALLERY) {
            modeChangeListener.onModeChange(MODE_FOLDER, -1);
            return true;
        }
        return false;
    }

    @Override
    public void onCancelClick(View v) {
        if (mSharePanel != null && mSharePanel.getVisibility() == View.VISIBLE) {
            mSharePanel.setVisibility(View.GONE);
            mShade.setVisibility(View.GONE);
        }
        if (mMode == MODE_FOLDER) {
            if (mFolderAdapter != null) {
                if (mFolderAdapter.isCheckStatus()) {
                    mActivity.doCancel(mFolderAdapter);
                } else {
                    mActivity.statisticsBack();
                    mActivity.finish();
                }
            } else {
                mActivity.statisticsBack();
                mActivity.finish();
            }
        } else if (mMode == MODE_GALLERY) {
            if (mGalleryAdapter != null) {
                if (mGalleryAdapter.isCheckStatus()) {
                    mActivity.doCancel(mGalleryAdapter);
                } else {
                    mActivity.statisticsBack();
                    mActivity.finish();
                }
            } else {
                mActivity.statisticsBack();
                mActivity.finish();
            }
        }
    }

    @Override
    public void onShareClick(View v) {
        initShareImageView();
        initShareImageViewAdapter(mActivity.getCheckedImageNum(), mActivity.getCheckedVideoNum());
    }

    @Override
    public void onDeleteClick(View v) {
        showDeleteConfirmDialog();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return false;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (isAdded()) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (mSharePanel != null && mSharePanel.getVisibility() == View.VISIBLE) {
                    mSharePanel.setVisibility(View.GONE);
                    mShade.setVisibility(View.GONE);
                    return true;
                }
                if (mMode == MODE_FOLDER) {
                    if (mFolderAdapter != null) {
                        if (mFolderAdapter.isCheckStatus()) {
                            mActivity.doCancel(mFolderAdapter);
                            return true;
                        }
                    }
                } else if (mMode == MODE_GALLERY) {
                    if (mGalleryAdapter != null) {
                        if (mGalleryAdapter.isCheckStatus()) {
                            mActivity.doCancel(mGalleryAdapter);
                        } else {
                            modeChangeListener.onModeChange(MODE_FOLDER, -1);
                        }
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    public void onNewIntent(Intent intent) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == GalleryActivity.REQUEST_CODE_PREVIEW) {
            if (data != null) {
                int refresh = data.getIntExtra(ImagePreviewActivity.NEED_RESFREH, ImagePreviewActivity.REFRESH_NONE);
                if (refresh == ImagePreviewActivity.REFRESH_CURRENT) {
                    setSelectionNeedRefresh(true);
                    refreshData();
                } else if (refresh == ImagePreviewActivity.REFRESH_CURRENT_AND_GALLERY) {
                    setSelectionNeedRefresh(true);
                    refreshData();
                    if (mDataListener != null) {
                        mDataListener.onDataChange(GalleryActivity.TYPE_FRAGMENT_GALLERY);
                    }
                }
            }
        }
    }

    @Override
    public ListGridAdapter getAdapter() {
        return mGalleryAdapter;
    }

    @Override
    public void doOnStart() {
        if (isAdded()) {
            refreshData();
        }
    }

    public int getPosition(ThumbnailBean bean) {
        if (mSelectPosition >= 0 && mSelectPosition < mFolderInfo.size()) {
            ArrayList<ThumbnailBean> datas = mFolderInfo.get(mSelectPosition).getData();
            if (datas != null) {
                return datas.indexOf(bean);
            }
        }
        return 0;
    }

    @Override
    public void startImagePreviewActivity(ThumbnailBean bean, int requestCode) {
        if (mFolderInfo != null && mSelectPosition >= 0 && mSelectPosition < mFolderInfo.size() && bean != null) {
            Intent i = new Intent(mActivity, ImagePreviewActivity.class);
            i.putExtra(ImagePreviewActivity.ENTRANCE, ImagePreviewActivity.FROM_OTHER_GALLERY);
            int position = getPosition(bean);
            i.putExtra(ImagePreviewActivity.POSITION, position);
            i.putExtra(ImagePreviewActivity.BUCKET_ID, mFolderInfo.get(mSelectPosition).getBucketId());
            mActivity.startActivityForResult(i, requestCode);
            /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                ActivityOptions transitionActivityOptions = ActivityOptions.makeSceneTransitionAnimation(mActivity);
                mActivity.startActivityForResult(i, requestCode, transitionActivityOptions.toBundle());
            } else {
                mActivity.startActivityForResult(i, requestCode);
//				mActivity.overridePendingTransition(R.anim.activity_bottom_in, 0);
            }*/
        }
    }

    @Override
    public void refreshData() {
        if (PermissionUtil.needRequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            return;
        }
        if ((mFolderAdapter == null || isNeedRefresh) && isCreated) {
            if (mMode == MODE_FOLDER) {
                isNeedRefresh = false;
                if (mActivity == null) {
                    return;
                }
                getGettingDataTask().executeOnExecutor(AsyncTask.DATABASE_THREAD_EXECUTOR, mActivity.getParams());
            } else if (mMode == MODE_GALLERY) {
                startGettingGalleryDataTask(mSelectPosition);
            }
        }
    }

    @Override
    public void forceRefreshData() {
        if (PermissionUtil.needRequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            return;
        }
        if (mMode == MODE_FOLDER) {
            isNeedRefresh = false;
            if (mActivity == null) {
                return;
            }
            getGettingDataTask().executeOnExecutor(AsyncTask.DATABASE_THREAD_EXECUTOR, mActivity.getParams());
        } else if (mMode == MODE_GALLERY) {
            startGettingGalleryDataTask(mSelectPosition);
        }
    }

    @Override
    public void setNeedRefresh(boolean flag) {
        isNeedRefresh = flag;
    }

    public void setSelectionNeedRefresh(boolean flag) {
        if (mSelectPosition != -1) {
            mFolderInfo.get(mSelectPosition).setNeedRefresh(flag);
        }
        setNeedRefresh(true);
    }

    @Override
    public int getImageNum() {
        if (mMode == MODE_FOLDER) {
            return mFolderInfo != null ? mFolderInfo.size() : 0;
        } else if (mMode == MODE_GALLERY) {
            ImageFolder bean = mFolderInfo.get(mSelectPosition);
            return bean.getData() != null ? bean.getData().size() : 0;
        }
        return 0;
    }

    /**
     * 获取数据的异步任务
     *
     * @return
     */
    public void startGettingGalleryDataTask(final int position) {
        if (mFolderInfo == null) return;
        final ImageFolder bean = mFolderInfo.get(position);
        if (bean.getData() != null && bean.getData().size() != 0 && !bean.isNeedRefresh()) {
            LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>(5, 1f, false);
            if (mNowTime == null) {
                mNowTime = new DateBean();
            }
            ArrayList<Object> datas = mActivity.uniformData(bean.getData(), map, mNowTime, COL_NUM);
            if (mGalleryAdapter == null) {
                mGalleryAdapter = new ListGridAdapter(datas, map, COL_NUM, mActivity, mNowTime.getDateTime());
                mGalleryAdapter.setOnCheckedChangeListener(mActivityListener);
            } else {
                mGalleryAdapter.setData(datas, map, mNowTime.getDateTime());
            }
            if (mGalleryListView != null) {
                mGalleryListView.setAdapter(mGalleryAdapter);
            }
        } else {
            if (mGalleryAdapter != null) {
                if (bean.getDir().startsWith(SPDataManager.getPhotoSaveLocation())) {//我们的相册路径包含这个删除的目录
                    if (mDataListener != null) {
                        mDataListener.onDataChange(GalleryActivity.TYPE_FRAGMENT_GALLERY);
                    }
                }
                LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>(5, 1f, false);
                ArrayList<Object> datas = new ArrayList<Object>();
                mNowTime = new DateBean(System.currentTimeMillis());
                mGalleryAdapter.setData(datas, map, mNowTime.getDateTime());
            }
            new AsyncTask<String, Integer, ArrayList<ThumbnailBean>>() {

                @Override
                protected ArrayList<ThumbnailBean> doInBackground(String... params) {
                    ArrayList<ThumbnailBean> datas = null;
                    int isNeedDeal = Integer.valueOf(params[0]);
                    if (isNeedDeal == 0) {
//                        datas = ImageHelper.getThumbnailBeanFromBucketId(mActivity, bean.getBucketId(), mActivity.isPickToCollageMode() ? 30 * 1000 : 0);
                        datas = ImageHelper.getThumbnailBeanFromBucketId(mActivity, bean.getBucketId());
                    } else if (isNeedDeal == 1) {
                        datas = ImageHelper.getImageThumbnailBeanFromBucketId(mActivity, bean.getBucketId());
                    } else if (isNeedDeal == 2) {
                        datas = ImageHelper.getVideoThumbnailBeanFromBucketId(mActivity, bean.getBucketId());
                    } else if (isNeedDeal == 3) {
                        datas = ImageHelper.getImageAndDynamicThumbnailBeanFromBucketId(mActivity, bean.getBucketId(), bean.getDir());
                    } else if (isNeedDeal == 4) {
                        datas = ImageHelper.getImageThumbnailBeanFromBucketId(mActivity, bean.getBucketId(), false);
                    }
                    return datas;
                }

                @Override
                protected void onPostExecute(ArrayList<ThumbnailBean> result) {
                    if (result == null || result.size() == 0) {//做一个保护
                        if (mContainerView.findViewById(R.id.layoutPermission).getVisibility() == View.GONE)
                            getEmptyGalleryView().setVisibility(View.VISIBLE);
                        setNeedRefresh(true);
                        return;
                    }
                    if (mEmptyGalleryView != null) {
                        mEmptyGalleryView.setVisibility(View.GONE);
                    }
                    bean.setData(result);
                    if (bean.getCount() != result.size()) {//数量改变刷新下
                        bean.setCount(result.size());
                    }
                    LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>(5, 1f, false);
                    if (mNowTime == null) {
                        mNowTime = new DateBean();
                    }
                    ArrayList<Object> datas = mActivity.uniformData(result, map, mNowTime, COL_NUM);
                    if (mGalleryAdapter == null) {
                        mGalleryAdapter = new ListGridAdapter(datas, map, COL_NUM, mActivity, mNowTime.getDateTime());
                        if (getArguments() != null) {
                            mGalleryAdapter.setFromWhere(getArguments().getString("fromWhere"));
                        }
                        mGalleryAdapter.setOnCheckedChangeListener(mActivityListener);
                    } else {
                        mGalleryAdapter.setData(datas, map, mNowTime.getDateTime());
                    }
                    if (mGalleryListView != null) {
                        mGalleryListView.setAdapter(mGalleryAdapter);
                    }
                }
            }.executeOnExecutor(AsyncTask.DATABASE_THREAD_EXECUTOR, mActivity.getParams());
        }
    }


    private void showGalleryListView(boolean visible) {
        if (visible) {
            if (mGalleryListView == null) {
                ViewStub vs = (ViewStub) mContainerView.findViewById(R.id.photo_list_viewstub_id);
                if (vs == null) {
                    mListPanel = mContainerView.findViewById(R.id.photo_list_layout_id);
                } else {
                    mListPanel = vs.inflate();
                }
                mGalleryListView = (ListView) mListPanel.findViewById(R.id.list);
            }
            mListPanel.setVisibility(View.VISIBLE);
        } else if (mListPanel != null) {
            mListPanel.setVisibility(View.GONE);
        }
    }

    /**
     * 获取数据的异步任务
     *
     * @return
     */
    public AsyncTask<String, Integer, ArrayList<ImageFolder>> getGettingDataTask() {
        AsyncTask<String, Integer, ArrayList<ImageFolder>> mGetDataTask = new AsyncTask<String, Integer, ArrayList<ImageFolder>>() {

            @Override
            protected ArrayList<ImageFolder> doInBackground(String... params) {
                int isNeedDeal = Integer.valueOf(params[0]);
                ArrayList<ImageFolder> datas = null;
                if (isNeedDeal == 0) {
//                    datas = ImageHelper.getAllFolderData(mActivity, mActivity.isPickToCollageMode() ? 30 * 1000 : 0);
                    datas = ImageHelper.getAllFolderData(mActivity);
                } else if (isNeedDeal == 1) {
                    datas = ImageHelper.getAllImageFolderData(mActivity);
                } else if (isNeedDeal == 2) {
                    datas = ImageHelper.getAllVideoFolderData(mActivity);
                } else if (isNeedDeal == 3) {
//                    datas = ImageHelper.getImageAndDynamicFolderData(mActivity);
                    datas = ImageHelper.getAllFolderData(mActivity);
                } else if (isNeedDeal == 4) {
                    datas = ImageHelper.getAllImageFolderData(mActivity, false);
                }
                return datas;
            }

            @Override
            protected void onPostExecute(ArrayList<ImageFolder> result) {
                if (result == null || result.size() == 0) {//做一个保护
                    if (mContainerView.findViewById(R.id.layoutPermission).getVisibility() == View.GONE)
                        getEmptyGalleryView().setVisibility(View.VISIBLE);
                    return;
                }
                if (mEmptyGalleryView != null) {
                    mEmptyGalleryView.setVisibility(View.GONE);
                }
                mFolderInfo = result;
                if (mFolderAdapter == null) {
                    mFolderAdapter = new FolderListAdapter(mActivity, mFolderInfo, mFolderView.getNumColumns());
                    mFolderAdapter.setOnCheckedChangeListener(mActivityListener);
                    mFolderAdapter.setOnModeChangeListener(modeChangeListener);
                } else {
                    mFolderAdapter.setData(mFolderInfo);
                }
                if (mFolderView != null) {
                    mFolderView.setAdapter(mFolderAdapter);
                }
                hidePermissionView();
            }
        };
        return mGetDataTask;
    }

    private View getEmptyGalleryView() {
        if (mEmptyGalleryView == null) {
            ViewStub vs = (ViewStub) mContainerView.findViewById(R.id.empty_gallery_viewstub_id);
            if (vs != null) {
                mEmptyGalleryView = vs.inflate();
            } else {
                mEmptyGalleryView = mContainerView.findViewById(R.id.empty_gallery_layout_id);
            }
            if (mEmptyGalleryView != null) {
                TextView title = (TextView) mEmptyGalleryView.findViewById(R.id.empty_title);
                TextView content = (TextView) mEmptyGalleryView.findViewById(R.id.empty_content);
                View bt = mEmptyGalleryView.findViewById(R.id.empty_bt);
                title.setText(R.string.gallery_empty_title);
                content.setText(R.string.gallery_empty_content);
                bt.setVisibility(View.VISIBLE);
                bt.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        //TODO:调用系统相机
//						Intent intent = new Intent(mActivity, MainActivity.class);
//						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
//								| Intent.FLAG_ACTIVITY_SINGLE_TOP
//								| Intent.FLAG_ACTIVITY_CLEAR_TOP);
//						intent.putExtra(ActionConstant.Extras.EXTRA_PAGE, MainActivity.PAGE_CAMERA);
//						mActivity.startActivity(intent);
                    }
                });
            }
        }
        return mEmptyGalleryView;
    }


    /**
     * 分享界面初始化
     */
    private void initShareImageView() {
        if (mSharePanel == null) {
            ViewStub vs = (ViewStub) mContainerView.findViewById(R.id.share_iamge_viewstub_id);
            if (vs == null) {
                mSharePanel = mContainerView.findViewById(R.id.share_iamge_layout_id);
            } else {
                mSharePanel = vs.inflate();
            }
            mShareImageView = (GridView) mSharePanel.findViewById(R.id.share_gridview);
            LinearLayout.LayoutParams param = (LinearLayout.LayoutParams) mShareImageView.getLayoutParams();
            param.height = ImageHelper.SCREEN_HEIGHT * 2 / 3 - mActivity.getResources().getDimensionPixelSize(R.dimen.share_textview_height);
            mShareImageView.setLayoutParams(param);
            mShareImageView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                                        int arg2, long arg3) {
                    if (arg1 instanceof ShareImageItem) {
                        ShareImageItem flag = (ShareImageItem) arg1;
                        ShareImageItem.ShareImageItemData siid = flag.getItemData();
                        boolean isInstall = ShareImageTools.getAppIsInstalled(mActivity, siid.getmPkgName());
                        if (isInstall) {
                            boolean result = ShareImageTools.startCommonShareMutilMediaActivity(mActivity,
                                    siid.getmPkgName(), siid.getmActivityName(), getSelectedData(), mActivity.getCheckedImageNum(), mActivity.getCheckedVideoNum());
                            mGalleryAdapter.setCheckStatus(false);
                            mSharePanel.setVisibility(View.GONE);
                            mShade.setVisibility(View.GONE);
                            if (!result) {
                                Toast.makeText(mActivity, R.string.not_install, Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(mActivity, R.string.not_install, Toast.LENGTH_SHORT).show();
                        }
                    }
                }

            });
            mShade.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    mSharePanel.setVisibility(View.GONE);
                    mShade.setVisibility(View.GONE);
                    return true;
                }
            });
        }
        mSharePanel.setVisibility(View.VISIBLE);
        mShade.setVisibility(View.VISIBLE);
    }

    /**
     * 初始化分享的Adapter
     */
    private void initShareImageViewAdapter(int imageNum, int videoNum) {
        if (mShareImageAdapter == null) {
            mShareImageAdapter = new ShareImageListAdapter(mActivity, ShareImageTools.getAllShareMutilMediaTools(mActivity, imageNum, videoNum));
            mShareImageView.setAdapter(mShareImageAdapter);
        } else {
            mShareImageAdapter.setData(ShareImageTools.getAllShareMutilMediaTools(mActivity, imageNum, videoNum));
            mShareImageAdapter.notifyDataSetChanged();
        }
    }

    private ArrayList<Uri> getSelectedData() {
        if (mMode == MODE_GALLERY) {
            ArrayList<ThumbnailBean> checkedList = mGalleryAdapter.getCheckedList();
            int len = checkedList.size();
            ArrayList<Uri> result = new ArrayList<Uri>(len);
            for (int i = 0; i < len; i++) {
                result.add(checkedList.get(i).getUri());
            }
            return result;
        }
        return null;
    }

    /**
     * 切tab时需要执行
     */
    public void setShareViewGone() {
        if (mShade != null && mShade.getVisibility() == View.VISIBLE) {
            if (mSharePanel != null) {
                mSharePanel.setVisibility(View.GONE);
            }
            if (mShade != null) {
                mShade.setVisibility(View.GONE);
            }
        }
    }

    public void doCheckAll(boolean checked) {
        if (mMode == MODE_FOLDER) {
            if (mFolderAdapter != null) {
                mFolderAdapter.checkAll(checked);
            }
        } else if (mMode == MODE_GALLERY) {
            if (mGalleryAdapter != null) {
                mGalleryAdapter.checkAll(checked);
            }
        }
    }

    public void doCancel() {
        if (mMode == MODE_FOLDER) {
            if (mFolderAdapter != null) {
                mActivity.doCancel(mFolderAdapter);
            }
        } else if (mMode == MODE_GALLERY) {
            if (mGalleryAdapter != null) {
                mActivity.doCancel(mGalleryAdapter);
            }
        }
    }

    public int getMode() {
        return mMode;
    }

    /**
     * 获取文件夹的名称
     *
     * @param position
     * @return
     */
    public String getFolderName(int position) {
        if (mFolderInfo.size() > position) {
            return mFolderInfo.get(position).getName();
        } else {
            return null;
        }
    }

    public int getSelectionIndex() {
        return mSelectPosition;
    }

    private void setFolderViewVisible(boolean visible) {
        if (mFolderView != null) {
            if (visible) {
                mFolderView.setVisibility(View.VISIBLE);
            } else {
                mFolderView.setVisibility(View.GONE);
            }
        }
    }

//	/**
//	 * 格式化数据
//	 * @param result
//	 */
//	private ArrayList<Object> uniformData(ArrayList<ThumbnailBean> result, HashMap<String, Integer> map){
//		
//		ArrayList<Object> datas = new ArrayList<Object>();
//		
//		int l = result.size();
//		if(l == 0){
//			return datas;
//		}
//		ArrayList<ThumbnailBean> data = null;
//		ThumbnailBean first = result.get(0);
//		DateBean now = new DateBean(first.getDate());
//		DateBean next;
//		mNowTime = System.currentTimeMillis();
//		DateBean today = new DateBean(mNowTime);
//		
//		int sum = 0;
//		/**
//		 * 处理第一个
//		 */
//		boolean hasToday;
//		boolean isAllToday = false;
//		if(now.isSameDay(today)){
//			datas.add(new SeparatorBean(mToday, GalleryActivity.TODAY_KEY));
//			hasToday = true;
//		} else{
//			if(now.isSameMonth(today)){
//				datas.add(new SeparatorBean(mMonth, now.getYearMonthString()));
//			} else{
//				datas.add(new SeparatorBean(now.getYearMonthString()));
//			}
//			hasToday = false;
//		}
//		data = new ArrayList<ThumbnailBean>();
//		datas.add(data);
//		data.add(first);
//		sum++;
//		int num = 1;
//		int i = 1;
//		if(hasToday){
//			for( ; i < l ; i++){
//				next = new DateBean(result.get(i).getDate());
//				if(next.isSameDay(today)){
//					if(num < COL_NUM){
//						data.add(result.get(i));
//					} else{
//						data = new ArrayList<ThumbnailBean>();
//						num = 0;
//						datas.add(data);
//						data.add(result.get(i));
//					}
//					num++;
//					sum++;
//				} else{
//					now = next;
//					if(hasToday){
//						map.put(GalleryActivity.TODAY_KEY, sum);
//						sum = 0;
//						if(now.isSameMonth(today)){
//							datas.add(new SeparatorBean(mMonth, now.getYearMonthString()));
//						} else{
//							datas.add(new SeparatorBean(now.getYearMonthString()));
//						}
//						data = new ArrayList<ThumbnailBean>();
//						num = 0;
//						datas.add(data);
//						data.add(result.get(i));
//						num++;
//						i++;
//						sum++;
//					}
//					break;
//				}
//			}
//			
//			/**
//			 * 这种是全是Today的情况
//			 */
//			if(map.get(GalleryActivity.TODAY_KEY) == null){
//				isAllToday = true;
//				map.put(GalleryActivity.TODAY_KEY, sum);
//				sum = 0;
//			}
//		}
//		
//		if(!isAllToday){
//			for( ; i < l ; i++){
//				next = new DateBean(result.get(i).getDate());
//				if(next.isSameMonth(now)){
//					if(num < COL_NUM){
//						data.add(result.get(i));
//					} else{
//						data = new ArrayList<ThumbnailBean>();
//						datas.add(data);
//						data.add(result.get(i));
//						num = 0;
//					}
//					num++;
//					sum++;
//				} else{
//					map.put(now.getYearMonthString(), sum);
//					sum = 0;
//					datas.add(new SeparatorBean(next.getYearMonthString()));
//					data = new ArrayList<ThumbnailBean>();
//					num = 0;
//					datas.add(data);
//					data.add(result.get(i));
//					num++;
//					sum++;
//				}
//				now = next;
//			}
//			map.put(now.getYearMonthString(), sum);
//		}
//		
////		for(String key: map.keySet()){
////			System.out.println("key = " + key + "  value = " + map.get(key));
////		}
//		
//		return datas;
//	}

//	/**
//	 * 格式化数据
//	 * @param result
//	 */
//	private ArrayList<Object> uniformData(ArrayList<ThumbnailBean> result, HashMap<String, Integer> map){
//
//		ArrayList<Object> datas = new ArrayList<Object>();
//
//		int l = result.size();
//		if(l == 0){
//			return datas;
//		}
//		ArrayList<ThumbnailBean> data = null;
//		ThumbnailBean first = result.get(0);
//		DateBean now = new DateBean(first.getDate());
//		DateBean next;
//		mNowTime = System.currentTimeMillis();
//		DateBean today = new DateBean(mNowTime);
//
//		int sum = 0;
//		/**
//		 * 处理第一个
//		 */
//		boolean hasToday;
//		boolean isAllToday = false;
//		if(now.isSameDay(today)){
//			datas.add(new SeparatorBean(mToday, GalleryActivity.TODAY_KEY));
//			hasToday = true;
//		} else{
//			if(now.isSameMonth(today)){
//				datas.add(new SeparatorBean(mMonth, GalleryActivity.MONTH_KEY));
//			} else{
//				datas.add(new SeparatorBean(now.getYearMonthString()));
//			}
//			hasToday = false;
//		}
//		data = new ArrayList<ThumbnailBean>();
//		datas.add(data);
//		data.add(first);
//		sum++;
//		int num = 1;
//		int i = 1;
//		if(hasToday){
//			for( ; i < l ; i++){
//				next = new DateBean(result.get(i).getDate());
//				if(next.isSameDay(today)){
//					if(num < COL_NUM){
//						data.add(result.get(i));
//					} else{
//						data = new ArrayList<ThumbnailBean>();
//						num = 0;
//						datas.add(data);
//						data.add(result.get(i));
//					}
//					num++;
//					sum++;
//				} else{
//					now = next;
//					if(hasToday){
//						map.put(GalleryActivity.TODAY_KEY, sum);
//						sum = 0;
//						if(now.isSameMonth(today)){
//							datas.add(new SeparatorBean(mMonth, GalleryActivity.MONTH_KEY));
//						} else{
//							datas.add(new SeparatorBean(now.getYearMonthString()));
//						}
//						data = new ArrayList<ThumbnailBean>();
//						num = 0;
//						datas.add(data);
//						data.add(result.get(i));
//						num++;
//						i++;
//						sum++;
//					}
//					break;
//				}
//			}
//
//			/**
//			 * 这种是全是Today的情况
//			 */
//			if(map.get(GalleryActivity.TODAY_KEY) == null){
//				isAllToday = true;
//				map.put(GalleryActivity.TODAY_KEY, sum);
//				sum = 0;
//			}
//		}
//
//		if(!isAllToday){
//			for( ; i < l ; i++){
//				next = new DateBean(result.get(i).getDate());
//				if(next.isSameMonth(now)){
//					if(num < COL_NUM){
//						data.add(result.get(i));
//					} else{
//						data = new ArrayList<ThumbnailBean>();
//						datas.add(data);
//						data.add(result.get(i));
//						num = 0;
//					}
//					num++;
//					sum++;
//				} else{
//					if(now.isSameMonth(today)){
//						map.put(GalleryActivity.MONTH_KEY, sum);
//					} else{
//						map.put(now.getYearMonthString(), sum);
//					}
//					sum = 0;
//					datas.add(new SeparatorBean(next.getYearMonthString()));
//					data = new ArrayList<ThumbnailBean>();
//					num = 0;
//					datas.add(data);
//					data.add(result.get(i));
//					num++;
//					sum++;
//				}
//				now = next;
//			}
//			if(now.isSameMonth(today)){
//				map.put(GalleryActivity.MONTH_KEY, sum);
//			} else{
//				map.put(now.getYearMonthString(), sum);
//			}
//		}
//
////		for(String key: map.keySet()){
////			System.out.println("key = " + key + "  value = " + map.get(key));
////		}
//
//		return datas;
//	}

    public void showDeleteConfirmDialog() {
        if (mDeleteConfirmDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
            builder.setTitle(R.string.tip);
            builder.setMessage(R.string.gallery_delete_dialog_message);
            builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mDeleteConfirmDialog.dismiss();
                }
            });
            builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    doDelete(mMode);
                    mDeleteConfirmDialog.dismiss();
                }
            });

            mDeleteConfirmDialog = builder.create();
            mDeleteConfirmDialog.setCancelable(true);
            mDeleteConfirmDialog.setCanceledOnTouchOutside(false);
            mDeleteConfirmDialog.show();
        } else {
            mDeleteConfirmDialog.show();
        }
    }

    /**
     * 处理点击delete
     */
    private void doDelete(int mode) {
        if (mode == MODE_GALLERY) {
            final ArrayList<ThumbnailBean> checkedList = mGalleryAdapter.getCheckedList();
            final int len = checkedList.size();
            if (len != 0) {
                ImageFolder imagef = mFolderInfo.get(mSelectPosition);
                final ArrayList<ThumbnailBean> allDatas = imagef.getData();
                if (allDatas != null) {
                    if (imagef.getDir().startsWith(SPDataManager.getPhotoSaveLocation())) {//我们的相册路径包含这个删除的目录
                        if (mDataListener != null) {
                            mDataListener.onDataChange(GalleryActivity.TYPE_FRAGMENT_GALLERY);
                        }
                    }
                    new AsyncTask<Void, Integer, ArrayList<ThumbnailBean>>() {
                        @Override
                        protected void onPreExecute() {
                            super.onPreExecute();
                            if (mProgressDialog == null) {
                                mProgressDialog = new ProgressDialog(mActivity, ProgressDialog.THEME_HOLO_LIGHT);
                                mProgressDialog.setCancelable(false);
                                mProgressDialog.setCanceledOnTouchOutside(false);
                                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                                mProgressDialog.setMax(checkedList.size());
                                mProgressDialog.setTitle(R.string.doing_delete);
                                mProgressDialog.setProgress(0);
                                mProgressDialog.show();
                            } else {
                                if (mProgressDialog.isShowing()) {
                                    mProgressDialog.dismiss();
                                }
                                mProgressDialog.setTitle(R.string.doing_delete);
                                mProgressDialog.setMax(checkedList.size());
                                mProgressDialog.show();
                                mProgressDialog.setProgress(0);
                            }
                        }

                        @Override
                        protected void onProgressUpdate(Integer... values) {
                            mProgressDialog.setProgress(mProgressDialog.getProgress() + values[0].intValue());
                            super.onProgressUpdate(values);
                        }

                        @Override
                        protected ArrayList<ThumbnailBean> doInBackground(Void... params) {
//							int l = checkedList.size();
//							for (int i = 0; i < l; i++) {
//								ThumbnailBean thumbnailBean = checkedList.get(i);
//								ImageHelper.deleteMediaByUri(mActivity, thumbnailBean.getUri(), thumbnailBean.getPath());
//								publishProgress(i + 1);
//							}
                            //最后一个参数传入false的原因是 other相册每一个都是一个单独的文件夹  不会存在多个文件夹的情况
                            final ArrayList<ThumbnailBean> deleteSuccessList = new ArrayList<ThumbnailBean>();
                            int successNumber = ImageHelper.deleteMedia(mActivity, ArrayUtil.copyArray(checkedList), new IDeleteListener<ThumbnailBean>() {
                                @Override
                                public void onDeleteFile(ThumbnailBean bean, boolean success) {
                                    publishProgress(1);
                                    if (success) {
                                        deleteSuccessList.add(bean);
                                    }
                                }

                                @Override
                                public void onDeleteFiles(boolean success) {//在这里不存在这种情况

                                }
                            }, false);
                            return deleteSuccessList;
                        }

                        @Override
                        protected void onPostExecute(ArrayList<ThumbnailBean> result) {
                            if (mProgressDialog.isShowing()) {
                                mProgressDialog.dismiss();
                            }
                            //只移除掉删除成功的
                            allDatas.removeAll(result);
                            if (allDatas.size() == 0) {
                                if (mContainerView.findViewById(R.id.layoutPermission).getVisibility() == View.GONE)
                                    getEmptyGalleryView().setVisibility(View.VISIBLE);
                            }
                            setNeedRefresh(true);
                            mGalleryAdapter.restoreCheckedList();
                            LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>(5, 1f, false);
                            if (mNowTime == null) {
                                mNowTime = new DateBean();
                            }
                            ArrayList<Object> datas = mActivity.uniformData(allDatas, map, mNowTime, COL_NUM);
                            mGalleryAdapter.setData(datas, map, mNowTime.getDateTime());
                            mGalleryAdapter.setCheckStatus(false);
                            super.onPostExecute(result);
                        }
                    }.executeOnExecutor(AsyncTask.DATABASE_THREAD_EXECUTOR);

                }
            }
        } else if (mode == MODE_FOLDER) {//删除整个文件夹
            final ArrayList<ImageFolder> checkedList = mFolderAdapter.getCheckedList();
            int len = checkedList.size();
            if (len != 0) {
                boolean needRefresh = false;
                int mediaSize = 0;
                for (int i = 0; i < len; i++) {
                    ImageFolder imageFolder = checkedList.get(i);
                    if (imageFolder.getDir().startsWith(SPDataManager.getPhotoSaveLocation())) {//我们的相册路径包含这个删除的目录checkedList.get(i).getDir()
                        needRefresh = true;
                    }
                    mediaSize += imageFolder.getCount();
                }
                final int max = mediaSize;
                if (needRefresh) {//我们的相册路径包含这个删除的目录
                    if (mDataListener != null) {
                        mDataListener.onDataChange(GalleryActivity.TYPE_FRAGMENT_GALLERY);
                    }
                }

                //恢复未选中状态并刷新页面
                mFolderAdapter.restoreCheckedList();
                mFolderAdapter.setCheckStatus(false);

                new AsyncTask<Void, Integer, ArrayList<ImageFolder>>() {
                    @Override
                    protected void onPreExecute() {
                        super.onPreExecute();
                        if (mProgressDialog == null) {
                            mProgressDialog = new ProgressDialog(mActivity, ProgressDialog.THEME_HOLO_LIGHT);
                            mProgressDialog.setCancelable(false);
                            mProgressDialog.setCanceledOnTouchOutside(false);
                            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                            mProgressDialog.setProgress(0);
                            mProgressDialog.setMax(max);
                            mProgressDialog.setTitle(R.string.doing_delete);
                            mProgressDialog.show();
                        } else {
                            if (mProgressDialog.isShowing()) {
                                mProgressDialog.dismiss();
                            }
                            mProgressDialog.setTitle(R.string.doing_delete);
                            mProgressDialog.setMax(max);
                            mProgressDialog.show();
                            mProgressDialog.setProgress(0);
                        }
                    }

                    @Override
                    protected void onProgressUpdate(Integer... values) {
                        mProgressDialog.setProgress(mProgressDialog.getProgress() + values[0].intValue());
                        super.onProgressUpdate(values);
                    }

                    @Override
                    protected ArrayList<ImageFolder> doInBackground(Void... params) {
                        int l = checkedList.size();
                        ArrayList<ImageFolder> deleteSuccessList = new ArrayList<ImageFolder>(l);
                        for (int i = 0; i < l; i++) {
                            ImageFolder imageFolder = checkedList.get(i);
                            final int baseSize = imageFolder.getCount();
                            int successNumber = ImageHelper.deleteMediaByBucketId(mActivity, imageFolder, new IDeleteListener<ThumbnailBean>() {
                                @Override
                                public void onDeleteFile(ThumbnailBean bean, boolean success) {//单个删除
                                    publishProgress(1);
                                }

                                @Override
                                public void onDeleteFiles(boolean success) {//整体删除
                                    publishProgress(baseSize);
                                }
                            });

                            if (successNumber >= baseSize) {
                                deleteSuccessList.add(imageFolder);
                            } else {//没有删除完成 更新状态
                                imageFolder.setCount(baseSize - successNumber);
                                imageFolder.setNeedRefresh(true);
                            }
                        }
                        return deleteSuccessList;
                    }

                    @Override
                    protected void onPostExecute(ArrayList<ImageFolder> result) {
                        super.onPostExecute(result);
                        //移除掉删除成功的 没有删除完全的
                        mFolderInfo.removeAll(result);
                        if (mFolderInfo.size() == 0) {//如果全部删除成功则显示空页面
                            if (mContainerView.findViewById(R.id.layoutPermission).getVisibility() == View.GONE)
                                getEmptyGalleryView().setVisibility(View.VISIBLE);
                        }
                        //刷新页面
                        mFolderAdapter.setData(mFolderInfo);

                        if (mProgressDialog.isShowing()) {
                            mProgressDialog.dismiss();
                        }
                        if (result.size() == checkedList.size()) {//完全删除成功
                            Toast.makeText(mActivity, R.string.delete_success, Toast.LENGTH_SHORT).show();
                        } else {//部分失败或者全部失败
                            Toast.makeText(mActivity, R.string.delete_fail, Toast.LENGTH_SHORT).show();
                        }
                    }
                }.executeOnExecutor(AsyncTask.DATABASE_THREAD_EXECUTOR);

            }
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
